<template>
	<div class="content-box scroll">
		<div class="content markdown-body" ref="markdownBody" v-if="contentNotNull" v-html="markedContent"></div>
		<div v-else class="loading">
			<span>加载数据中，请稍后</span>
		</div>
	</div>
</template>

<script setup="props" lang="ts">
import { ref, onMounted, computed } from 'vue';
import { API } from '@v/utils/API';
import { useRootStore } from '@v/store';
import { isURL } from '@v/methods/regexp';
import { generateMD } from '@v/methods/generateMD';

const store = useRootStore();

const markdownBody = ref<HTMLDivElement>();

const props = defineProps({
	content: String,
});

function readComplete() {
	let id = store.fileInfoMessageId;

	if (id !== -1) {
		store.setMessage('update', { id, type: 'success', message: `文件读取完成 "${store.filePath}"` });

		store.setFileInfoMessageId(-1);
	}
}

// Markdown 内容是否为空
const contentNotNull = computed(() => {
	if (store.fileInfo) {
		return typeof store.fileInfo.content === 'string';
	} else {
		return false;
	}
});

// Markdown 内容
const markedContent = computed(() => {
	if (props.content) {
		const str = generateMD(props.content);

		readComplete();

		return str;
	} else {
		if (contentNotNull) {
			return '空文档';
		} else {
			return '';
		}
	}
});

onMounted(() => {
	if (markdownBody.value) {
		// 阻止文档区的所有a标签的跳转或打开新标签页
		markdownBody.value.addEventListener('click', (event) => {
			if (event.target && (event.target as HTMLDivElement).tagName === 'A') {
				event.preventDefault(); // 禁止默认行为（跳转或打开新标签页）
				event.stopPropagation(); // 阻止事件冒泡

				const ANode = event.target as HTMLAnchorElement;

				// 如果是转的链接时url则通过默认浏览器打开链接
				if (isURL(ANode.href)) {
					API.send('open-external', ANode.href);
				}
			}
		});
	}
});
</script>

<style scoped lang="scss">
.content-box {
	max-width: 100%;
	height: 100%;
	.content {
		max-width: 1024px;
		min-width: 700px;
		min-height: calc(100% - 60px);
		padding: 30px;
		margin: 0 auto;
	}
	.loading {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 18px;
	}
}
</style>
